package com.bluexmicro.android.upgradebox.screen.configure

import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.net.Uri
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.bluexmicro.android.upgradebox.R
import com.google.accompanist.flowlayout.FlowRow

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ConfigureScreen(
    configureViewModel: ConfigureViewModel,
    onPickFileListener: () -> Unit,
    onUpgradeListener: () -> Unit
) {

    val resources = remember {
        configureViewModel.resources
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text("OTA配置", color = MaterialTheme.colorScheme.onPrimary)
                },
                actions = {
                    Button(
                        onClick = onUpgradeListener,
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color.Blue,
                            disabledContentColor = Color.Gray
                        ),
                        enabled = resources.size > 0
                    ) {
                        Text("开始")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(containerColor = MaterialTheme.colorScheme.primary)
            )
        }
    ) { paddingValues ->
        LazyColumn(
            modifier = Modifier.padding(paddingValues)
        ) {
            item {
                Spacer(modifier = Modifier.height(16.dp))
                H1TextView("1. 选择固件/素材", modifier = Modifier.padding(start = 16.dp))
                Spacer(modifier = Modifier.height(16.dp))
            }
            itemsIndexed(resources) { _, res ->
                ResourceItemView(res) {
                    configureViewModel.onResourceRemoved(res)
                }
            }
            item {
                OutlinedButton(
                    onClick = onPickFileListener,
                    modifier = Modifier.padding(start = 32.dp, end = 8.dp)
                ) {
                    Text("选择")
                }
                Spacer(modifier = Modifier.height(32.dp))
            }

            item {
                H1TextView("2. 设置过滤条件", modifier = Modifier.padding(start = 16.dp))
                Spacer(modifier = Modifier.height(8.dp))

            }

            item {
                Column(
                    modifier = Modifier.padding(start = 32.dp, end = 16.dp)
                ) {
                    RssiFilterView(configureViewModel)
                    CompanyFilterView(configureViewModel)
                    NameFilterView(configureViewModel)
                    MacFilterView(configureViewModel)
                }
            }

            item {
                Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxWidth()) {
                    VersionTipText(true)
                }
                Spacer(modifier = Modifier.height(16.dp))
            }
        }
    }
}


@Composable
fun RssiFilterView(viewModel: ConfigureViewModel) {
    var rssiThreshold by remember {
        viewModel.rssiThreshold
    }
    H2TextView("限制信号强度:(${(rssiThreshold - 127).toInt()}mdb)")
    DescTextView("外设离手机越远，信号强度越小，设置一个阈值，过滤距离远的设备（天线不正常的外设信号也差）")
    Row(
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text("-127", style = MaterialTheme.typography.labelSmall)
        Slider(rssiThreshold, valueRange = 0f..127f, steps = 127, onValueChange = {
            rssiThreshold = it
            viewModel.saveRssi()
        }, modifier = Modifier.weight(1f))
        Text("0", style = MaterialTheme.typography.labelSmall)
    }
    Divider(
        thickness = Dp.Hairline,
        modifier = Modifier.padding(
            top = 8.dp,
            bottom = 16.dp
        )
    )
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NameFilterView(viewModel: ConfigureViewModel) {
    var showDialog by remember {
        mutableStateOf(false)
    }

    val nameFilters = remember {
        viewModel.nameFilters
    }
    H2TextView("根据匹配的名字")
    Spacer(modifier = Modifier.height(8.dp))
    FlowRow(
        mainAxisSpacing = 4.dp,
        crossAxisSpacing = 4.dp
    ) {
        nameFilters.map {
            TagView(it) {
                viewModel.removeNameFilter(it)
            }
        }
    }
    OutlinedIconButton(onClick = {
        showDialog = true
    }) {
        Icon(
            painter = painterResource(id = R.drawable.ic_baseline_add_24),
            null,
            tint = MaterialTheme.colorScheme.onBackground,
            modifier = Modifier.size(16.dp)
                .defaultMinSize(minWidth = 0.dp, minHeight = 0.dp)
        )
    }
    Divider(
        thickness = Dp.Hairline,
        modifier = Modifier.padding(
            top = 8.dp,
            bottom = 16.dp
        )
    )
    if (showDialog) {
        var payload by remember {
            mutableStateOf("")
        }
        AlertDialog(
            onDismissRequest = {
                showDialog = false
            },
            confirmButton = {
                Button(onClick = {
                    viewModel.addNameFilter(payload)
                    showDialog = false
                }) {
                    Text("提交")
                }
            },
            dismissButton = {
                TextButton(onClick = {
                    showDialog = false
                }) {
                    Text("取消")
                }
            },
            title = {
                Text("根据设备名称过滤出匹配的设备")
            },
            text = {
                TextField(value = payload, placeholder = {
                    Text("请输入设备名称，可以是不完整的名称")
                }, onValueChange = {
                    if (it.isEmpty() || it.length <= 10) {
                        payload = it
                    }
                })
            })
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MacFilterView(viewModel: ConfigureViewModel) {
    var showDialog by remember {
        mutableStateOf(false)
    }
    val macFilters = remember {
        viewModel.macFilters
    }
    H2TextView("根据匹配的MAC地址")
    DescTextView("假如要升级的设备是同一批次的,可以按照地址段过滤出当前批次的设备")
    Spacer(modifier = Modifier.height(8.dp))
    FlowRow(
        mainAxisSpacing = 4.dp,
        crossAxisSpacing = 4.dp
    ) {
        macFilters.map {
            TagView(it) {
                viewModel.removeMacFilter(it)
            }
        }
    }
    OutlinedIconButton(onClick = {
        showDialog = true
    }) {
        Icon(
            painter = painterResource(id = R.drawable.ic_baseline_add_24),
            null,
            tint = MaterialTheme.colorScheme.onBackground,
            modifier = Modifier.size(16.dp)
                .defaultMinSize(minWidth = 0.dp, minHeight = 0.dp)
        )
    }
    Divider(
        thickness = Dp.Hairline,
        modifier = Modifier.padding(
            top = 8.dp,
            bottom = 16.dp
        )
    )
    if (showDialog) {
        var payload by remember {
            mutableStateOf("")
        }
        AlertDialog(
            onDismissRequest = {
                showDialog = false
            },
            confirmButton = {
                Button(onClick = {
                    showDialog = false
                    viewModel.addMacFilter(payload)
                }) {
                    Text("提交")
                }
            },
            dismissButton = {
                TextButton(onClick = {
                    showDialog = false
                }) {
                    Text("取消")
                }
            },
            title = {
                Text("添加匹配的MAC地址")
            },
            text = {
                TextField(value = payload, placeholder = {
                    Text("请输入MAC，可以是不完整的MAC地址")
                }, onValueChange = {
                    if (it.isEmpty() || (it.matches(macRegex) && it.length <= 17)) {
                        payload = it
                    }
                })
            })
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CompanyFilterView(viewModel: ConfigureViewModel) {
    var showDialog by remember {
        mutableStateOf(false)
    }
    val companys = remember {
        viewModel.companyIdFilters
    }
    H2TextView("选择匹配的公司ID")
    DescTextView("假如设备在广播包中设置厂商自定义数据，且设置CompanyId，可以根据该配置过滤出有效的设备")
    Spacer(modifier = Modifier.height(8.dp))
    FlowRow(
        mainAxisSpacing = 4.dp,
        crossAxisSpacing = 4.dp
    ) {
        companys.map {
            TagView("0x${it.padStart(4, '0').uppercase()}") {
                viewModel.removeCompanyFilter(it)
            }
        }
    }
    OutlinedIconButton(onClick = {
        showDialog = true
    }) {
        Icon(
            painter = painterResource(id = R.drawable.ic_baseline_add_24),
            null,
            tint = MaterialTheme.colorScheme.onBackground,
            modifier = Modifier.size(16.dp)
                .defaultMinSize(minWidth = 0.dp, minHeight = 0.dp)
        )
    }

    Divider(
        thickness = Dp.Hairline,
        modifier = Modifier.padding(
            top = 8.dp,
            bottom = 16.dp
        )
    )
    if (showDialog) {
        var payload by remember {
            mutableStateOf("")
        }
        AlertDialog(
            onDismissRequest = {
                showDialog = false
            },
            confirmButton = {
                Button(onClick = {
                    viewModel.addCompanyFilter(payload)
                    showDialog = false
                }) {
                    Text("提交")
                }
            },
            dismissButton = {
                TextButton(onClick = {
                    showDialog = false
                }) {
                    Text("取消")
                }
            },
            title = {
                Text("请输入公司Id")
            },
            text = {
                TextField(value = payload, placeholder = {
                    Text("请输入4位16进制数")
                }, onValueChange = {
                    if (it.isEmpty() || (it.matches(hexRegex) && it.length <= 4)) {
                        payload = it
                    }
                })
            })
    }
}

val hexRegex = "^[A-Fa-f0-9]+$".toRegex()
val macRegex = "^[A-Fa-f0-9:]+$".toRegex() //todo 优化

///////////////////////////////////////////////////////////////////////////
// Configure 多次使用的组件
///////////////////////////////////////////////////////////////////////////

@Composable
fun ResourceItemView(res: Resource, onRemoveListener: () -> Unit) {
    Card(
        modifier = Modifier.padding(horizontal = 32.dp, vertical = 4.dp).fillMaxWidth()
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(
                modifier = Modifier.weight(1f).padding(8.dp)
            ) {
                Text(res.file.name, style = MaterialTheme.typography.labelMedium)
                Text(
                    "address: ${res.address?.toString(16)}",
                    style = MaterialTheme.typography.labelSmall,
                    color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.5f)
                )
            }
            IconButton(onClick = onRemoveListener) {
                Icon(
                    painter = painterResource(id = R.drawable.ic_close),
                    null,
                    tint = MaterialTheme.colorScheme.onBackground,
                    modifier = Modifier.size(16.dp)
                        .defaultMinSize(minWidth = 0.dp, minHeight = 0.dp)
                )
            }
        }
    }
}

@Composable
fun H1TextView(title: String, modifier: Modifier = Modifier) {
    Text(
        title,
        modifier = modifier,
        style = MaterialTheme.typography.titleMedium
    )
}

@Composable
fun H2TextView(title: String, modifier: Modifier = Modifier) {
    Text(
        title,
        modifier = modifier,
        style = MaterialTheme.typography.titleSmall
    )
}

@Composable
fun DescTextView(desc: String) {
    Text(
        desc,
        style = MaterialTheme.typography.bodySmall,
        color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.5f)
    )
}

@Composable
fun TagView(content: String, onRemoveListener: () -> Unit) {
    Row(
        modifier = Modifier
            .background(Color.LightGray, shape = RoundedCornerShape(size = 8.dp))
            .padding(horizontal = 4.dp).clickable {
                onRemoveListener.invoke()
            },
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            content,
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onPrimary
        )
        Icon(
            painter = painterResource(id = R.drawable.ic_close),
            null,
            tint = MaterialTheme.colorScheme.onPrimary,
            modifier = Modifier.size(16.dp).defaultMinSize(minWidth = 0.dp, minHeight = 0.dp)
        )
    }
}

@Composable
fun VersionTipText(enable: Boolean) {
    val context = LocalContext.current
    val version = try {
        val info = context.packageManager.getPackageInfo(context.packageName, 0)
        info.versionName
    } catch (ignore: Exception) {
        "Unknown Version"
    }
    val tmp = if (isDebug(context)) "（Debug）" else ""
    OutlinedButton(enabled = enable, onClick = {
        //OutlinedButton在disable状态下能触发onclick
        if (enable) {
            val uri = Uri.parse("https://www.pgyer.com/8RhF");    //设置跳转的网站
            val intent = Intent(Intent.ACTION_VIEW, uri)
            context.startActivity(intent)
        }
    }, shape = RoundedCornerShape(64.dp)) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text("下载新版本", style = MaterialTheme.typography.labelMedium)
            Text(
                "当前版本: $version$tmp",
                style = MaterialTheme.typography.labelSmall,
                color = MaterialTheme.colorScheme.onBackground
            )
        }
    }

}

private fun isDebug(context: Context): Boolean {
    return context.applicationInfo != null && (context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0)
}




